package com.neusoft.work.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neusoft.work.dao.CareLevelProjectDao;
import com.neusoft.work.dao.CareProjectDao;
import com.neusoft.work.dao.CustomerCareLevelDao;
import com.neusoft.work.dao.CustomerCarePlanDao;
import com.neusoft.work.dao.CustomerDao;
import com.neusoft.work.po.CareLevelProject;
import com.neusoft.work.po.CareProject;
import com.neusoft.work.po.Customer;
import com.neusoft.work.po.CustomerCareLevel;
import com.neusoft.work.po.CustomerCarePlan;
import com.neusoft.work.po.ResponseBean;
import com.neusoft.work.service.CustomerCareLevelService;

@Service
public class CustomerCareLevelServiceImpl implements CustomerCareLevelService {

	@Autowired
	private CustomerCareLevelDao customerCareLevelDao;

	@Autowired
	private CareLevelProjectDao careLevelProjectDao;

	@Autowired
	private CareProjectDao careProjectDao;

	@Autowired
	private CustomerCarePlanDao customerCarePlanDao;
	
	@Autowired
	private CustomerDao customerDao;

    @Override
    public ResponseBean<CustomerCareLevel> getCustomerCareLevel(Integer customerId) {
        QueryWrapper<CustomerCareLevel> qw = new QueryWrapper<>();
        qw.eq("customerId", customerId);
        CustomerCareLevel ccl = customerCareLevelDao.selectOne(qw);
        if (ccl != null) {
            return new ResponseBean<>(ccl);
        } else {
            return new ResponseBean<>(500, "该客户尚未设置护理级别");
        }
    }

    @Override
    @Transactional
    public ResponseBean<Integer> addCustomerCareLevel(CustomerCareLevel ccl) {
        // 如果已存在就更新，否则插入
        QueryWrapper<CustomerCareLevel> qw = new QueryWrapper<>();
        qw.eq("customerId", ccl.getCustomerId());
        CustomerCareLevel exist = customerCareLevelDao.selectOne(qw);

        int rows;
        if (exist != null) {
            // 更新级别
            exist.setCareLevelId(ccl.getCareLevelId());
            rows = customerCareLevelDao.updateById(exist);
        } else {
            rows = customerCareLevelDao.insert(ccl);
        }

        if (rows > 0) {
            return new ResponseBean<>(ccl.getCustomerId());
        } else {
            return new ResponseBean<>(500, "设置护理级别失败");
        }
    }

    @Override
    @Transactional
    public ResponseBean<Integer> removeCareLevel(Integer customerId) {
        // 1. 先查出客户当前的 careLevelId
        QueryWrapper<CustomerCareLevel> qwCcl = new QueryWrapper<>();
        qwCcl.eq("customerId", customerId);
        CustomerCareLevel existing = customerCareLevelDao.selectOne(qwCcl);
        if (existing == null) {
            return new ResponseBean<>(500, "客户尚未设置护理级别");
        }
        Integer careLevelId = existing.getCareLevelId();

        // 2. 删除 CustomerCareLevel 关联
        int delCcl = customerCareLevelDao.delete(qwCcl);

        // 3. 找出该级别对应的所有项目 ID
        QueryWrapper<CareLevelProject> qwClp = new QueryWrapper<>();
        qwClp.eq("careLevelId", careLevelId);
        List<CareLevelProject> clpList = careLevelProjectDao.selectList(qwClp);
        if (!clpList.isEmpty()) {
            List<Integer> projectIds = clpList.stream()
                .map(CareLevelProject::getCareProjectId)
                .toList();

            // 4. 根据 projectIds 查询出对应的 projectCode 列表
            List<CareProject> projects = careProjectDao.selectBatchIds(projectIds);
            List<String> codes = projects.stream()
                .map(CareProject::getCode)
                .toList();

            if (!codes.isEmpty()) {
                // 5. 删除 CustomerCarePlan 中 customerId 且 careProjectCode 属于 codes 的记录
                QueryWrapper<CustomerCarePlan> qwPlan = new QueryWrapper<>();
                qwPlan.eq("customerId", customerId)
                      .in("careProjectCode", codes)
                      .eq("source", 1);  // 只删除护理级别附带的项目
                customerCarePlanDao.delete(qwPlan);
            }
        }
        
        // 6.判断客户是否还有其他护理项目，若无则修改为自理老人
        Long remainingPlans = customerCarePlanDao.selectCount(
            new QueryWrapper<CustomerCarePlan>()
                .eq("customerId", customerId)
                .eq("status", 1) // 可选：只统计有效的护理计划
        );
        Customer customer = new Customer();
        customer.setId(customerId);
        customer.setType(remainingPlans > 0 ? 2 : 1);  // 2=护理，1=自理
        customerDao.updateById(customer);

        if (delCcl > 0) {
            return new ResponseBean<>(customerId);
        } else {
            return new ResponseBean<>(500, "移除护理级别失败");
        }
    }
}
